// pages/classfy/classfy.js
const goodsService = require('../../service/goodsService.js')
const utils = require('../../utils/util.js');
// load promise 
require('../../utils/wx-pro.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectId: '',
    goodsKindList: [],
    goodsList: [],
    showToast: false,
    toastMsg: ''
  },

  //错误提示
  showToastFuc(msg) {
    this.setData({
      showToast: true,
      toastMsg: msg
    })
    setTimeout(() => {
      this.setData({
        showToast: false,
        toastMsg: ''
      })
    }, 2000)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var cate_id = app.globalData.cate_id
    if (!cate_id){
      this.getGoodsKinds()
    }
  },

  onShow: function () {
    var cate_id = app.globalData.cate_id
    if (cate_id) {
      this.setData({
        selectId: cate_id
      })
      this.getGoodsKinds()
    }
  },

  changeKind(event){
    if (event.currentTarget.dataset.id != this.data.selectId){
      this.setData({
        selectId: event.currentTarget.dataset.id
      })
      this.getGoodsList({ cateId: this.data.selectId, pageSize: 999 })
    }
  },

  getGoodsKinds(){
    goodsService.getGoodsKinds().then(data => {
      if (data.code == 200) {
        this.setData({
          goodsKindList: data.response.xcxGoodsClass,
        })
        if(!this.data.selectId){
          this.setData({
            selectId: data.response.xcxGoodsClass[0].gcId
          })
        }
        this.getGoodsList({ cateId: this.data.selectId, pageSize: 999 })
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch(() => {
        console.log('error')
      })
  },
  getGoodsList(params) {
    params.shopId = JSON.parse(wx.getStorageSync('selectShopInfo')).id
    goodsService.getGoodsByGoodsKind(params).then(data => {
      if (data.code == 200) {
        app.globalData.cate_id = ""
        var goods = []
        var str = data.response.xcxGoodsList
        var goodsNo = []
        for (var i of str) {
          if (i.stockNum <= 0) {
            var obj = i
            goodsNo.push(obj)
          } else {
            var obj1 = i
            goods.push(obj1)
          }
        }
        console.log(goods)
        var goodsList = goodsNo.reduce(function (coll, item) {
          coll.push(item);
          return coll;
        }, goods)
        this.setData({
          goodsList: goodsList
        })
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch(() => {
        console.log('error')
      })
  }






















  
})